package models

import (
	"github.com/beego/beego/v2/client/orm"
)

// OperationLog 操作日志模型
type OperationLog struct {
	BaseModel
	UserId        int64  `orm:"" json:"user_id"`                // 用户ID
	Username      string `orm:"size(64)" json:"username"`       // 用户名
	Method        string `orm:"size(10)" json:"method"`         // 请求方法 GET/POST/PUT/DELETE
	Path          string `orm:"size(255)" json:"path"`          // 请求路径
	Ip            string `orm:"size(64)" json:"ip"`             // IP地址
	Status        int    `orm:"" json:"status"`                 // 响应状态码
	OperationType string `orm:"size(64)" json:"operation_type"` // 操作类型
	Description   string `orm:"size(255)" json:"description"`   // 操作描述
	Duration      int64  `orm:"" json:"duration"`               // 请求耗时(毫秒)
}

// TableName 设置表名
func (o *OperationLog) TableName() string {
	return "ss_operation_log"
}

// AddOperationLog 添加操作日志
func AddOperationLog(log *OperationLog) error {
	o := orm.NewOrm()
	log.BeforeInsert()
	_, err := o.Insert(log)
	return err
}

// GetOperationLogs 获取操作日志列表
func GetOperationLogs(page, pageSize int, startTime, endTime int64, username, operationType string) ([]*OperationLog, int64, error) {
	o := orm.NewOrm()
	qs := o.QueryTable(new(OperationLog))

	// 添加查询条件
	if startTime > 0 {
		qs = qs.Filter("created_at__gte", startTime)
	}
	if endTime > 0 {
		qs = qs.Filter("created_at__lte", endTime)
	}
	if username != "" {
		qs = qs.Filter("username__contains", username)
	}
	if operationType != "" {
		qs = qs.Filter("operation_type", operationType)
	}

	// 获取总数
	total, err := qs.Count()
	if err != nil {
		return nil, 0, err
	}

	// 分页查询
	var logs []*OperationLog
	_, err = qs.OrderBy("-created_at").Limit(pageSize, (page-1)*pageSize).All(&logs)
	if err != nil {
		return nil, 0, err
	}

	return logs, total, nil
}

// GetOperationLogTypes 获取操作类型列表
func GetOperationLogTypes() ([]string, error) {
	o := orm.NewOrm()
	var types []string
	_, err := o.Raw("SELECT DISTINCT operation_type FROM operation_log WHERE is_deleted = 0").QueryRows(&types)
	return types, err
}

// CreateOperationLog 创建操作日志
func CreateOperationLog(userId int64, operationType string, description string, method string, ip string, franchiseId int64) error {
	log := &OperationLog{
		UserId:        userId,
		OperationType: operationType,
		Description:   description,
		Method:        method,
		Ip:            ip,
	}

	// 设置加盟商ID
	log.FranchiseId = franchiseId

	return AddOperationLog(log)
}
